package com.android.systemui.ios.wall;

import android.content.Context;
import android.content.SharedPreferences;
import android.provider.Settings;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

public class SharedUtil {

    private static SharedPreferences getShare(Context context) {
        return context.getSharedPreferences("share", 0);
    }

    public static void putArrSetting(Context context, ArrayList<ItemSetting> arrayList) {
        try {
            JSONObject object = new JSONObject();
            JSONArray array = new JSONArray();
            for (ItemSetting item : arrayList) {
                array.put(item.toJson());
            }
            object.put("data", array);
            getShare(context).edit().putString("arr_setting", object.toString()).apply();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public static ArrayList<ItemSetting> getArrSetting(Context context) {
        ArrayList<ItemSetting> arrayList = new ArrayList<>();
        String string = getShare(context).getString("arr_setting", "");
        if (!string.isEmpty()) {
            try {
                JSONObject object = new JSONObject(string);
                JSONArray array = object.getJSONArray("data");
                for (int i = 0; i < array.length(); i++) {
                    JSONObject child = array.getJSONObject(i);
                    arrayList.add(new ItemSetting(child));
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            if (arrayList.isEmpty()) {
                arrayList.add(new ItemSetting(Settings.System.getInt(context.getContentResolver(), "live_wallpaper_type", 0)));
                putArrSetting(context, arrayList);
            }
        }
        return arrayList;
    }

    public static void putTheme(Context context, int i) {
        getShare(context).edit().putInt("theme_choose", i).apply();
    }

    public static int getIdThemeCurrent(Context context) {
        return getShare(context).getInt("theme_choose", 1);
    }
}
